#!/bin/tcsh -ef
####
#
#############################################################################
#                                                                           #
# Title: Refine Params (Only Tilted Images)                                 #
#                                                                           #
# (C) 2dx.org, GNU Plublic License.                                         #
#                                                                           #
# Created..........: 02/20/2006                                             #
# Last Modification: 02/20/2006                                             #
# Author...........: 2dx.org                                                #
#                                                                           #
#############################################################################
#
# SORTORDER: 78
#
# MANUAL: This script applies ttrefine or mmboxref to the dataset.
#
# MANUAL: TTREFINE refines defocus, astigmatism, tiltaxis and tiltangle in images of thin tilted crystals.
#
# MANUAL: <B>VERY IMPORTANT NOTE</B>: The quality of image data required for success in this type of least squares refinement is high, particularly if more than one parameter is to be refined. BE VERY CAREFUL.
#
# MANUAL: For tilted images, you can use it ot refine the Defocus, the Astigmatism, the Tilt Axis, the Tilt Angle, or all together.
#
# DISPLAY: refine
# DISPLAY: refine_cyc
# DISPLAY: refine_reference
# DISPLAY: refine_overwrite
# DISPLAY: spcgrp
# DISPLAY: imagesidelength
# DISPLAY: magnification
# DISPLAY: stepdigitizer
# DISPLAY: TLTAXIS
# DISPLAY: TLTANG 
# DISPLAY: TLTAXA 
# DISPLAY: TAXA 
# DISPLAY: TANGL
# DISPLAY: realcell
# DISPLAY: realang
# DISPLAY: defocus
# DISPLAY: beamtilt
# DISPLAY: RESMAX
# DISPLAY: CS
# DISPLAY: KV
# DISPLAY: tempkeep
# DISPLAY: comment
# DISPLAY: SYM
# DISPLAY: phaori
# DISPLAY: revhk
# DISPLAY: rot90
# DISPLAY: rot180
# DISPLAY: sgnxch
# DISPLAY: revhnd
# DISPLAY: ctfrev
# DISPLAY: revxsgn
# DISPLAY: lattice
#
#$end_local_vars
#
set proc_2dx = ""
set bin_2dx = ""
#
set refine = ""
set refine_cyc = ""
set refine_reference = ""
set refine_overwrite = ""
set SYM = ""
set imagename = ""
set defocus = ""
set imagenumber = ""
set lattice = ""
set imagesidelength = ""
set magnification = ""
set stepdigitizer = ""
set tempkeep = ""
set RESMIN = ""
set RESMAX = ""
set TLTAXIS = ""
set TLTANG = ""
set realcell = ""
set realang = ""
set phacon = ""
set CS = ""
set KV = ""
set TLTANG = ""
set det_tilt = ""
set tempkeep = ""
set phaori = ""
set revhk = ""
set rot180 = ""
set rot90 = ""
set sgnxch = ""
set revhnd = ""
set ctfrev = ""
set revxsgn = ""
#
#$end_vars
#
echo bin_2dx = ${bin_2dx}
echo proc_2dx = ${proc_2dx}
#
set ccp4_setup = 'y'
set IS_2DX = yes
source ${proc_2dx}/initialize
#
set scriptname = 2dx_refineParams
\rm -f LOGS/${scriptname}.results
#
echo "<<@evaluate>>"
#
set date = `date`
echo date = ${date}
#
source ${proc_2dx}/2dx_sym2spcgrp_sub.com
#
set ABANG = `echo $realang | awk '{s=180-$1} END {print s}'`
echo ABANG = ${ABANG}
#
set istilt = `echo $TLTANG | awk '{if ( -25.0 < $1 && $1 < 25.0 ) {s = 0} else {s = 1}} END {print s}'`
#
if ( ${rot180} == 'y' ) then
  set rot180val = '1'
else
  set rot180val = '0'
endif
#
if ( ${rot90} == 'y' ) then
  set rot90val = '1'
  ${proc_2dx}/protest "ERROR: rot90 Not yet implemented."
else
  set rot90val = '0'
endif
#
if ( ${revhk} == 'y' ) then
  set revhkval = '1'
else
  set revhkval = '0'
endif
#
if ( ${revhnd} == 'y' ) then
  set revhndval = '1'
  ${proc_2dx}/protest "ERROR: revhnd Not yet implemented."
else
  set revhndval = '0'
endif
#
if ( ${ctfrev} == 'y' ) then
  set ctfrevval = '1'
else
  set ctfrevval = '0'
endif
#
echo sgnxch = ${sgnxch}
#
set phaori_local = ${phaori}
#
if ( ${sgnxch} == "y" ) then
  set sgnxchval = 1
  set phaorix = `echo ${phaori_local} | cut -d\, -f1 `
  set phaoriy = `echo ${phaori_local} | cut -d\, -f2 | awk '{ s = -$1 } END { print s }'`
  set phaori_local = `echo ${phaorix},${phaoriy}`
else
  set sgnxchval = 0
endif
#
echo revxsgn = ${revxsgn}
if ( ${revxsgn} == "y" ) then
  set revxsgnval = 1
  set phaorix = `echo ${phaori_local} | cut -d\, -f1 | awk '{ s = -$1 } END { print s }'`
  set phaoriy = `echo ${phaori_local} | cut -d\, -f2 `
  set phaori_local = `echo ${phaorix},${phaoriy}`
else
  set revxsgnval = 0
endif
#
echo "<<@progress: 1>>"
#
echo ":: "
${proc_2dx}/linblock "ToDo: We need here an option that calls ttboxref"
echo ":: "
#
#     refine         1 = Defocus refined
#                    2 = Defocus and astigmatism refined.
#                    3 = Tiltaxis refined.
#                    4 = Tiltangle refined.
#                    5 = All five parameters refined.
#
#  TTREFINE refines ctf and tilt parameters in tilted images.
#  1 :   IMODE,NCYC,FSHIFT,LIST,MTZ,MAXIM,LISTS,ISHIFT,IREF     (*)
#  2 :   FULL NAME OF INPUT FILE
#  3 :   ISIZEX,ISIZEY,DSTEP,XMAG,CS,KV                         (*)
#  4 :   NUMSPOT, NOH, NOK, NHOR, NVERT                         (*)
#  5 :   RESMIN, RESMAX                                         (*)
#  6 :   AX, AY, BX, BY                                         (*)
#  7 :   ISPGRP,ORIGH,ORIGK,REVHK,ROT180,SGNXCH                 (*)
#  8 :   DFMID1,DFMID2,ANGAST,TLTAXIS,TLTANGL                   (*)
#  9 :   FC=F SIGFC=SIGF PHCAL=PHS FOM=FOM ##           (MTZ CARD)
#
\rm -f TMP123333.tmp
\rm -f TMP124444.tmp
#
set fft_file = FFTIR/cor${imagename}.fft.mrc
#
if ( ${refine} == "1" || ${refine} == "2" || ${refine} == "3" || ${refine} == "4" || ${refine} == "5"  ) then
  #
  if ( ${refine} == "1" ) then
    ${proc_2dx}/linblock "Refining Defocus."
  endif
  if ( ${refine} == "2" ) then
    ${proc_2dx}/linblock "Refining Defocus and Astigmatism."
  endif
  if ( ${refine} == "3" ) then
    ${proc_2dx}/linblock "Refining Tiltaxis."
  endif
  if ( ${refine} == "4" ) then
    ${proc_2dx}/linblock "Refining Tiltangle."
  endif
  if ( ${refine} == "5" ) then
    ${proc_2dx}/linblock "Refining Defocus, Astigma., Tiltaxis and Tiltangle."
  endif
  #
  echo "<<@progress: 30>>"
  #
  if ( ! -e ${fft_file} ) then
    ${proc_2dx}/protest "ERROR: ${fft_file} not found."
  endif
  #
  if ( ${refine_reference} == '0' ) then
    #############################################################################
    ${proc_2dx}/linblock "2dx_ttrefine - To refine parameters. Using FFT itself."
    #############################################################################
    #
    ${bin_2dx}/2dx_ttrefine.exe << eot
${refine} ${refine_cyc} 0.20 F F T F F 1         ! IMODE,NCYC,FSHIFT,LIST,MTZ,MAXIM,LISTS,ISHIFT,IREF
${fft_file}
${imagesidelength} ${imagesidelength} ${stepdigitizer} ${magnification} ${CS} ${KV}  ! ISIZEX,ISIZEY,DSTEP,XMAG,CS,KVOLT
0 30 30 19 19                                ! NUMSPOT, NOH, NOK, NHOR, NVERT
${RESMIN} ${RESMAX}                          ! RESMIN, RESMAX
${lattice},${ABANG}                             ! AX, AY, BX, BY  , ABANG
${spcgrp} ${phaori_local} ${revhkval} ${rot180val} ${sgnxchval} ${rot90val} ${ctfrevval}          ! ISPGRP,ORIGH,ORIGK,REVHK,ROT180,SGNXCH,ROT90,CTFREV
${defocus} ${TLTAXIS} ${TLTANG}              ! DFMID1,DFMID2,ANGAST,TLTAXIS,TLTANGL
eot
    #
  else
    #
    #############################################################################
    ${proc_2dx}/linblock "2dx_ttrefine - To refine parameters."
    #############################################################################
    #
    set INFILE = '../merge/merge3Dref_MRClefthanded.mtz'
    if ( ! -e ${INFILE} ) then
      set INFILE1 = '../../merge/merge3Dref_MRClefthanded.mtz'
      if ( ! -e ${INFILE1} ) then
        set INFILE2 = '../merge/merge2Dref_MRClefthanded.mtz'
        if ( ! -e ${INFILE2} ) then
          set INFILE3 = '../../merge/merge2Dref_MRClefthanded.mtz'
          if ( ! -e ${INFILE3} ) then
            ${proc_2dx}/linblock "ERROR: Neither ${INFILE} nor ${INFILE1}"
            ${proc_2dx}/linblock "           nor ${INFILE2} nor ${INFILE3} found"
            ${proc_2dx}/protest "2dx_ttrefine: Aborting."
          else
            set INFILE = ${INFILE3}
          endif
        else
          set INFILE = ${INFILE2}
        endif
      else
        set INFILE = ${INFILE1}
      endif
    endif
    #
    ${proc_2dx}/linblock "Using ${INFILE} as reference."
    #
    setenv HKLIN ${INFILE}
    #
    ${bin_2dx}/2dx_ttrefine.exe << eot
${refine} ${refine_cyc} 0.20 F T F F F 1         ! IMODE,NCYC,FSHIFT,LIST,MTZ,MAXIM,LISTS,ISHIFT,IREF
${fft_file}
${imagesidelength} ${imagesidelength} ${stepdigitizer} ${magnification} ${CS} ${KV}  ! ISIZEX,ISIZEY,DSTEP,XMAG,CS,KVOLT
0 30 30 19 19                                ! NUMSPOT, NOH, NOK, NHOR, NVERT
${RESMIN} ${RESMAX}                          ! RESMIN, RESMAX
${lattice},${ABANG}                             ! AX, AY, BX, BY  , ABANG
${spcgrp} ${phaori_local} ${revhkval} ${rot180val} ${sgnxchval} ${rot90val} ${ctfrevval}          ! ISPGRP,ORIGH,ORIGK,REVHK,ROT180,SGNXCH,ROT90,CTFREV
${defocus} ${TLTAXIS} ${TLTANG}              ! DFMID1,DFMID2,ANGAST,TLTAXIS,TLTANGL
LABIN AMP=F PHASE=PHI FOM=FOM SIG=SIGF 
eot
    #
  endif
  #
  if ( ! -e TMP123333.tmp ) then
    ${proc_2dx}/protest "2dx_ttrefine: ERROR occured."
  else
    cat TMP124444.tmp
    source TMP123333.tmp
    \rm -f TMP124444.tmp
    \rm -f TMP123333.tmp
    #     refine         1 = Defocus refined
    #                    2 = Defocus and astigmatism refined.
    #                    3 = Tiltaxis refined.
    #                    4 = Tiltangle refined.
    #                    5 = All five parameters refined.
    if ( ${refine} == "1" || ${refine} == "2" || ${refine} == "5" ) then
      set defocus = "${refine_defocus}"
      if ( ${refine_overwrite} == "y" ) then
        echo ":: Overwriting with new values:"
        echo ":: set defocus = ${defocus}"
        echo "set defocus = "\"${defocus}\" >> LOGS/${scriptname}.results
      else
        echo ":: Only test run."
        echo ":: Not used: set defocus = ${defocus}"
      endif
    endif
    if ( ${refine} == "3" || ${refine} == "4" || ${refine} == "5") then
      set TLTAXIS = ${refine_TLTAXIS}
      set TLTANGL = ${refine_TLTANGL}
      set TLTAXA  = ${refine_TLTAXA}
      set TAXA    = ${refine_TAXA}
      set TANGL   = ${refine_TANGL}
      if ( ${refine_overwrite} == "y" ) then
        echo ":: Overwriting with new values:"
        echo ":: set TLTAXIS = ${TLTAXIS}"
        echo ":: set TLTANGL = ${TLTANGL}"
        echo ":: set TLTAXA  = ${TLTAXA}"
        echo ":: set TAXA    = ${TAXA}" 
        echo ":: set TANGL   = ${TANGL}"
        #
        echo "set TLTAXIS = ${TLTAXIS}" >> LOGS/${scriptname}.results
        echo "set TLTANGL = ${TLTANGL}" >> LOGS/${scriptname}.results
        echo "set TLTAXA  = ${TLTAXA}" >> LOGS/${scriptname}.results
        echo "set TAXA    = ${TAXA}" >> LOGS/${scriptname}.results
        echo "set TANGL   = ${TANGL}" >> LOGS/${scriptname}.results
        #
        echo "set TTREFINE_TLTAXIS = ${TLTAXIS}" >> LOGS/${scriptname}.results
        echo "set TTREFINE_TLTANGL = ${TLTANGL}" >> LOGS/${scriptname}.results
        echo "set TTREFINE_TLTAXA  = ${TLTAXA}" >> LOGS/${scriptname}.results
        echo "set TTREFINE_TAXA    = ${TAXA}" >> LOGS/${scriptname}.results
        echo "set TTREFINE_TANGL   = ${TANGL}" >> LOGS/${scriptname}.results
        #
        echo ":: Only test run."
        echo ":: Not used: TLTAXIS = ${TLTAXIS}"
        echo ":: Not used: TLTANGL = ${TLTANGL}"
        echo ":: Not used: TLTAXA  = ${TLTAXA}"
        echo ":: Not used: TAXA    = ${TAXA}" 
        echo ":: Not used: TANGL   = ${TANGL}"
      endif
    endif
  endif
  # echo "set TTREFINE_done = y" >> LOGS/${scriptname}.results
  #
else
  #############################################################################
  ${proc_2dx}/linblock "Nothing done."
  #############################################################################
endif
#
echo "# IMAGE-IMPORTANT: "FFTIR/${imagename}_fft.mrc "<FFT of Image>" >> LOGS/${scriptname}.results
echo "# IMAGE-IMPORTANT: "FFTIR/${imagename}_red_fft.mrc "<FFT of Downsampled Image>" >> LOGS/${scriptname}.results
echo "# IMAGE-IMPORTANT: ${fft_file} <FFT of Unbent Image>" >> LOGS/${scriptname}.results
#
echo "<<@progress: 100>>"
#
##########################################################################
${proc_2dx}/linblock "${scriptname} - normal end."
##########################################################################
#
#
#

